<template>
  <div class="app-container nursing-plan-page">
    <!-- 搜索表单 -->
    <div class="search-container" v-show="showSearch">
      <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="120px" class="search-form">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="护理计划名称" prop="planName">
              <el-input 
                v-model="queryParams.planName" 
                placeholder="请输入护理计划名称" 
                clearable 
                @keyup.enter="handleQuery" 
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="状态" prop="status">
              <el-select 
                v-model="queryParams.status" 
                placeholder="请选择状态" 
                clearable
                style="width: 130px;"
                :popper-append-to-body="false"
                popper-class="status-select-dropdown"
              >
                <el-option label="启用" :value="1" />
                <el-option label="禁用" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label=" " class="search-buttons">
              <el-button type="default" icon="Refresh" @click="resetQuery">重置</el-button>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 操作按钮行 -->
    <el-row :gutter="10" class="toolbar-row">
      <el-col :span="12">
        <el-button
          type="primary"
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['service:plan:add']"
          class="action-btn"
        >新增护理计划</el-button>
        <el-button 
          type="success" 
          plain 
          icon="Edit" 
          :disabled="single" 
          @click="handleUpdate" 
          v-hasPermi="['service:plan:edit']"
          class="action-btn"
        >修改</el-button>
        <el-button 
          type="danger" 
          plain 
          icon="Delete" 
          :disabled="multiple" 
          @click="handleDelete" 
          v-hasPermi="['service:plan:remove']"
          class="action-btn"
        >删除</el-button>
      </el-col>
      <el-col :span="12" class="text-right">
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-col>
    </el-row>

    <!-- 数据表格 -->
    <el-table 
      v-loading="loading" 
      :data="planList" 
      @selection-change="handleSelectionChange"
      class="nursing-plan-table"
      stripe
      border
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" label="序号" width="80" align="center" />
      <el-table-column label="护理计划名称" align="center" prop="planName" min-width="100" :show-overflow-tooltip="true"/>
      <el-table-column label="总价(30天)" align="center" width="140">
        <template #default="scope">
          <span class="price-text">{{ formatCurrency(scope.row.totalPrice ?? scope.row.extraField1) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="creatorName" width="120">
        <template #default="scope">{{ scope.row.creatorName || scope.row.creator }}</template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope"><span>{{ parseTime(scope.row.createTime) }}</span></template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'" effect="plain">
            {{ scope.row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="260" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['service:plan:edit']">编辑</el-button>
          <el-button link type="primary" icon="View" @click="handleView(scope.row)">查看</el-button>
          <el-button link :type="scope.row.status === 1 ? 'warning' : 'success'" @click="handleToggleStatus(scope.row)">
            {{ scope.row.status === 1 ? '禁用' : '启用' }}
          </el-button>
          <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['service:plan:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
      class="nursing-plan-pagination"
    />

    <!-- 添加或修改护理计划对话框 -->
    <el-dialog :title="title" v-model="open" width="1100px" height="800px" append-to-body class="nursing-plan-dialog">
      <el-form ref="planRef" :model="form" :rules="rules" label-width="120px" class="nursing-plan-form">
        <el-form-item label="护理计划名称" prop="planName" class="form-item-inline">
          <el-input 
            v-model="form.planName" 
            placeholder="请输入护理计划名称" 
            maxlength="50"
            show-word-limit
            class="full-width-input"
          />
        </el-form-item>
        <el-form-item label="护理项目" required>
          <el-table :data="form.planItems" border style="width: 100%">
            <el-table-column label="护理项目名称" width="220">
              <template #default="scope">
                <el-select v-model="scope.row.itemId" placeholder="请选择" filterable style="width: 200px;">
                  <el-option v-for="opt in itemOptions" :key="opt.id" :label="opt.name" :value="opt.id" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="期望服务时间" width="160">
              <template #default="scope">
                <el-time-picker v-model="scope.row.serviceTime" placeholder="请选择" style="width: 140px;" format="HH:mm" value-format="HH:mm" />
              </template>
            </el-table-column>
            <el-table-column label="执行周期" width="140">
              <template #default="scope">
                <el-select v-model="scope.row.period" style="width: 120px;">
                  <el-option label="每日" value="DAILY" />
                  <el-option label="每周" value="WEEKLY" />
                  <el-option label="每月" value="MONTHLY" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="执行次数（次）" width="160">
              <template #default="scope">
                <el-input-number v-model="scope.row.times" :min="1" :max="99" />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120" align="center">
              <template #default="scope">
                <el-button circle icon="Plus" @click="addPlanItem(scope.$index)" />
                <el-button circle icon="Minus" @click="removePlanItem(scope.$index)" :disabled="form.planItems.length === 1" />
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="预计总价(30天)">
          <div style="font-size: 16px; font-weight: 600; color: #333;">
            {{ formatCurrency(previewTotalPrice) }}
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看护理计划 -->
    <el-dialog title="查看护理计划" v-model="openView" width="800px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="护理计划名称">{{ viewRow.planName }}</el-descriptions-item>
        <el-descriptions-item label="创建人">{{ viewRow.creatorName || viewRow.creator }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ parseTime(viewRow.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="总价(30天)">{{ formatCurrency(viewRow.totalPrice ?? viewRow.extraField1) }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="viewRow.status === 1 ? 'success' : 'danger'">
            {{ viewRow.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
      </el-descriptions>
      
      <div style="margin-top: 20px;">
        <h4>护理项目明细</h4>
        <el-table :data="viewRow.nursingItemPlanBindingList || []" border style="width: 100%">
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column label="护理项目名称" prop="nursingItemName" align="center" />
          <el-table-column label="期望服务时间" prop="serviceTime" align="center" width="140">
            <template #default="scope">
              <span>{{ scope.row.serviceTime ? scope.row.serviceTime.substring(0, 5) : '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="执行周期" prop="executionCycle" align="center" width="120">
            <template #default="scope">
              <span>{{ getCycleText(scope.row.executionCycle) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="执行次数（次）" prop="executionFrequency" align="center" width="140" />
          <el-table-column label="状态" align="center" width="100">
            <template #default="scope">
              <el-tag :type="getItemStatus(scope.row) === '禁用' ? 'danger' : 'success'">
                {{ getItemStatus(scope.row) }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="openView = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Plan">
import { listPlan, getPlan, delPlan, addPlan, updatePlan } from "@/api/system/plan"
import { listItem } from "@/api/system/item.js"

const { proxy } = getCurrentInstance()

const planList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    planName: null,
    status: null
  },
  rules: {
    planName: [
      { required: true, message: "计划名称不能为空", trigger: "blur" }
    ],
    createTime: [
      { required: true, message: "创建时间不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)
const { sys_normal_disable } = proxy.useDict("sys_normal_disable")

// 货币格式化
function formatCurrency(val) {
  if (val === undefined || val === null || val === '') return '-'
  const num = typeof val === 'number' ? val : Number(val)
  if (Number.isNaN(num)) return '-'
  return '¥' + num.toFixed(2)
}

/** 查询护理计划列表 */
function getList() {
  loading.value = true
  listPlan(queryParams.value).then(response => {
    console.log(response);
    planList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    planName: null,
    createTime: null,
    status: 1, // 默认启用状态
    planItems: [
      { itemId: null, serviceTime: "08:00", period: "DAILY", times: 1 }
    ]
  }
  proxy.resetForm("planRef")
}
// 查看
const openView = ref(false)
const viewRow = ref({})
function handleView(row) {
  viewRow.value = { ...row }
  openView.value = true
  }

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加护理计划"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  
  console.log('编辑护理计划，row数据:', row)
  console.log('row.nursingItemPlanBindingList:', row.nursingItemPlanBindingList)
  
  // 先尝试使用表格行数据
  if (row.nursingItemPlanBindingList && Array.isArray(row.nursingItemPlanBindingList) && row.nursingItemPlanBindingList.length > 0) {
    console.log('使用表格行数据进行回显')
    
    form.value = {
      ...row,
      planItems: row.nursingItemPlanBindingList.map(it => ({
        itemId: it.nursingItemId,
        serviceTime: it.serviceTime ? it.serviceTime.substring(0, 5) : "08:00",
        period: getPeriodValue(it.executionCycle),
        times: it.executionFrequency || 1
      }))
    }
    
    console.log('使用表格数据回显的form.value:', form.value)
    console.log('使用表格数据回显的planItems:', form.value.planItems)
    
    open.value = true
    title.value = "修改护理计划"
    return
  }
  
  // 如果表格数据没有nursingItemPlanBindingList，则调用API
  const _id = row.id || ids.value
  
  if (!_id) {
    proxy.$modal.msgError("数据异常，无法获取计划ID")
    return
  }
  
  console.log('表格数据无nursingItemPlanBindingList，调用API获取ID:', _id)

  getPlan(_id).then(response => {
    console.log('getPlan返回的完整数据:', response)
    console.log('response.data:', response.data)
    
    const resp = response.data || {}
    console.log('处理后的resp:', resp)
    console.log('nursingItemPlanBindingList:', resp.nursingItemPlanBindingList)
    
    form.value = {
      ...resp,
      planItems: Array.isArray(resp.nursingItemPlanBindingList) && resp.nursingItemPlanBindingList.length
        ? resp.nursingItemPlanBindingList.map(it => ({
            itemId: it.nursingItemId,
            serviceTime: it.serviceTime ? it.serviceTime.substring(0, 5) : "08:00",
            period: getPeriodValue(it.executionCycle),
            times: it.executionFrequency || 1
          }))
        : [{ itemId: null, serviceTime: "08:00", period: "DAILY", times: 1 }]
    }
    
    console.log('最终form.value:', form.value)
    console.log('form.value.planItems:', form.value.planItems)
    
    open.value = true
    title.value = "修改护理计划"
  }).catch(error => {
    console.error('获取护理计划详情失败:', error)
    proxy.$modal.msgError("获取护理计划详情失败")
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["planRef"].validate(valid => {
    if (valid) {
      // 转换数据格式以匹配后端期望的结构
      const submitData = {
        ...form.value,
        nursingItemPlanBindingList: form.value.planItems
          .filter(item => item.itemId != null) // 过滤掉空的护理项目
          .map(item => ({
            nursingItemId: item.itemId,
            serviceTime: item.serviceTime + ':00', // 转换为 HH:mm:ss 格式
            executionCycle: getCycleNumber(item.period),
            executionFrequency: item.times
          }))
      }
      // 删除前端使用的 planItems 字段
      delete submitData.planItems

      console.log('提交的数据:', submitData)
      
      if (form.value.id != null) {
        updatePlan(submitData).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        }).catch(error => {
        console.error('修改失败:', error)
        proxy.$modal.msgError("修改失败")
        })
      } else {
        addPlan(submitData).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        }).catch(error => {
          console.error('新增失败:', error)
          proxy.$modal.msgError("新增失败")
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除护理计划编号为"' + _ids + '"的数据项？').then(function() {
    return delPlan(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('service/plan/export', {
    ...queryParams.value
  }, `plan_${new Date().getTime()}.xlsx`)
}

getList()

// 启用/禁用
function handleToggleStatus(row) {
  const nextStatus = row.status === 1 ? 0 : 1
  const text = nextStatus === 1 ? "启用" : "禁用"
  const payload = { id: row.id, status: nextStatus }
  proxy.$modal.confirm('确认要' + text + '该计划吗?').then(function () {
    return updatePlan(payload)
  }).then(() => {
    proxy.$modal.msgSuccess(text + "成功")
    getList()
  }).catch(() => {})
}

// 计划项目行操作 & 下拉
function addPlanItem(index) {
  form.value.planItems.splice(index + 1, 0, { itemId: null, serviceTime: "08:00", period: "DAILY", times: 1 })
}
function removePlanItem(index) {
  if (form.value.planItems.length > 1) {
    form.value.planItems.splice(index, 1)
  }
}
const itemOptions = ref([])
function loadItemOptions() {
  listItem({ pageNum: 1, pageSize: 1000, status: 1 }).then(res => {
    itemOptions.value = res.rows || []
  })
}
onMounted(() => {
  loadItemOptions()
})

// 辅助函数：执行周期数字转文本
function getCycleText(cycle) {
  const cycleMap = { 1: '每日', 2: '每周', 3: '每月' }
  return cycleMap[cycle] || '-'
}

// 辅助函数：获取护理项目状态
function getItemStatus(item) {
  // 根据执行周期判断使用哪个字段
  // 每日任务（executionCycle=1）：使用extraField1
  // 每周/每月任务（executionCycle=2/3）：使用extraField2
  if (item.executionCycle === 1) {
    return item.extraField1 === '禁用' ? '禁用' : '启用'
  } else if (item.executionCycle === 2 || item.executionCycle === 3) {
    return item.extraField2 === '禁用' ? '禁用' : '启用'
  }
  return '启用'
}

// 辅助函数：执行周期数字转值
function getPeriodValue(cycle) {
  const cycleMap = { 1: 'DAILY', 2: 'WEEKLY', 3: 'MONTHLY' }
  return cycleMap[cycle] || 'DAILY'
}

// 辅助函数：执行周期值转数字
function getCycleNumber(period) {
  const periodMap = { 'DAILY': 1, 'WEEKLY': 2, 'MONTHLY': 3 }
  return periodMap[period] || 1
}

// 前端总价预览（与后端一致的近似规则）
const previewTotalPrice = computed(() => {
  if (!form.value || !Array.isArray(form.value.planItems)) return 0
  const priceMap = new Map(itemOptions.value.map(it => [it.id, Number(it.price || 0)]))
  let sum = 0
  for (const it of form.value.planItems) {
    if (!it || !it.itemId) continue
    const unit = priceMap.get(it.itemId) || 0
    const freq = Number(it.times || 1)
    const cycle = getCycleNumber(it.period)
    let times = 0
    if (cycle === 1) times = 30 * freq
    else if (cycle === 2) times = 4 * freq
    else times = 1 * freq
    sum += unit * times
  }
  return Number(sum.toFixed(2))
})
</script>

<style scoped lang="scss">
/* 页面整体样式 */
.nursing-plan-page {
  background: #f5f7fa;
  min-height: calc(100vh - 84px);

  /* 搜索容器 */
  .search-container {
    background: #fff;
    padding: 20px;
    margin-bottom: 16px;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.06);

    .search-form {
      :deep(.el-form-item) {
        margin-bottom: 0;
      }

      :deep(.el-form-item__label) {
        font-weight: 500;
        color: #333;
      }

      .search-buttons {
        display: flex;
        justify-content: flex-end;
        
        :deep(.el-form-item__content) {
          justify-content: flex-end;
        }

        .el-button {
          min-width: 80px;
        }
      }
    }
  }

  /* 工具栏 */
  .toolbar-row {
    background: #fff;
    padding: 16px 20px;
    margin-bottom: 16px;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.06);
    align-items: center;

    .action-btn {
      margin-right: 12px;
      font-weight: 500;
    }

    .text-right {
      display: flex;
      justify-content: flex-end;
      align-items: center;
    }
  }

  /* 表格样式 */
  .nursing-plan-table {
    background: #fff;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);

    :deep(.el-table__header) {
      th {
        background: #f5f7fa;
        color: #333;
        font-weight: 600;
        font-size: 14px;
        padding: 16px 0;
      }
    }

    :deep(.el-table__body) {
      td {
        padding: 14px 0;
        font-size: 14px;
        color: #606266;
      }

      .el-table__row:hover {
        background-color: #f5f7fa;
      }
    }

    /* 价格文字样式 */
    .price-text {
      color: #00CC99;
      font-weight: 600;
      font-size: 15px;
    }

    /* 操作按钮样式 */
    :deep(.el-button--text) {
      padding: 4px 8px;
      margin: 0 4px;
    }
  }
}

/* 护理计划对话框样式 */
.nursing-plan-dialog {
  :deep(.el-dialog__header) {
    background: linear-gradient(135deg, #00CC99 0%, #00b386 100%);
    padding: 20px;
    margin: 0;

    .el-dialog__title {
      color: #fff;
      font-size: 18px;
      font-weight: 600;
    }

    .el-dialog__headerbtn {
      top: 20px;
      right: 20px;

      .el-dialog__close {
        color: #fff;
        font-size: 20px;

        &:hover {
          color: #f0f0f0;
        }
      }
    }
  }

  :deep(.el-dialog__body) {
    padding: 30px;
  }

  .nursing-plan-form {
    .form-item-inline {
      display: flex;
      align-items: flex-start;
      margin-bottom: 24px;

      :deep(.el-form-item__label) {
        flex-shrink: 0;
        font-weight: 500;
        color: #333;
        font-size: 14px;
        line-height: 40px;
        padding-right: 12px;
      }

      :deep(.el-form-item__content) {
        flex: 1;
        display: flex;
        align-items: flex-start;
      }

      /* 全宽输入框 */
      .full-width-input {
        width: 100%;
      }
    }
  }

  /* 对话框底部按钮 */
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    padding: 10px 0 0;

    .el-button {
      min-width: 90px;
      padding: 10px 20px;
      font-weight: 500;
    }
  }
}

/* 输入框获取焦点时的样式 */
:deep(.el-input__inner:focus),
:deep(.el-textarea__inner:focus) {
  border-color: #00CC99;
  box-shadow: 0 0 0 2px rgba(0, 204, 153, 0.1);
}

/* 分页样式 */
:deep(.el-pagination) {
  margin-top: 20px;
  padding: 16px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.06);
  justify-content: center;
}

/* 通用样式 */
.text-right {
  text-align: right;
}

.mb8 {
  margin-bottom: 8px;
}
</style>

<style lang="scss">
/* 状态下拉框样式 - 全局样式 */
.status-select-dropdown {
  min-width: 150px !important;
  
  .el-select-dropdown__item {
    padding: 12px 16px;
    font-size: 14px;
  }
}
</style>
